<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="考核类型" prop="checkType">
        <el-select v-model="formData.checkType" placeholder="请选择考核类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CHECK_TYPE2)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="考核分数" prop="score">
        <el-input v-model="formData.score" disabled placeholder="请输入考核分数" />
        <el-button @click="openScoreForm" type="primary">打分</el-button>
      </el-form-item>
      <el-form-item label="考核总分" prop="totalScore">
        <el-input v-model="formData.totalScore" disabled placeholder="请输入考核总分" />
      </el-form-item>
      <el-form-item label="跟随人员" prop="participant">
        <el-input v-model="formData.participant" placeholder="请输入跟随人员" />
      </el-form-item>
      <el-form-item label="项目负责人" prop="projectManager">
        <el-input v-model="formData.projectManager" placeholder="请输入项目负责人" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <ScoreForm ref="scoreFormRef" @success="getScoreData" />

  <CleanScoreForm ref="cleanScoreFormRef" @success="getScoreData" />
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { ProjectApi } from '@/api/project/project'

import ScoreForm from './ScoreForm.vue'
import CleanScoreForm from "./CleanScoreForm.vue";

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  projectId: undefined,
  checkType: undefined,
  assessmentBatchId: undefined,
  score: undefined,
  totalScore: undefined,
  participant: undefined,
  projectManager: undefined,
})


// 打分详细
const areaRecordList = ref<{
  id: number;
  areaId: number;
  assessmentBatchId: number,
  projectId: number;
  areaDetailId: number | undefined;
  checkType: number;
  remark: string;
}[]>([])



const formRules = reactive({
  projectId: [{ required: true, message: '项目编号不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number, projectId: number, assessmentBatchId: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.projectId = projectId
  formData.value.assessmentBatchId = assessmentBatchId
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProjectApi.getCheckRecord(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      if (data.checkType === 4) {
        await ProjectApi.createCheckRecord(data)
        await ProjectApi.addCleanAreaRecordList(areaRecordList.value)
      } else {
        await ProjectApi.createCheckRecord(data)
        await ProjectApi.addAreaRecordList(areaRecordList.value)
      }
      message.success(t('common.createSuccess'))
    } else {
      if (data.checkType === 4) {
        await ProjectApi.updateCheckRecord(data)
        await ProjectApi.updateCleanAreaRecordList(areaRecordList.value)
      } else {
        await ProjectApi.updateCheckRecord(data)
        await ProjectApi.updateAreaRecordList(areaRecordList.value)
      }
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    projectId: undefined,
    assessmentBatchId: undefined,
    checkType: undefined,
    score: undefined,
    totalScore: undefined,
    participant: undefined,
    projectManager: undefined,
  }
  formRef.value?.resetFields()
}

/** 添加/修改操作 */
const scoreFormRef = ref()
const cleanScoreFormRef = ref()
const openScoreForm = () => {
  if (!formData.value.checkType) {
    message.error('请选择一个检查类型')
    return
  }
  if (formData.value.checkType === 4) {
    cleanScoreFormRef.value.open(formType.value, formData.value.projectId, formData.value.assessmentBatchId)
  } else {
    scoreFormRef.value.open(formType.value, formData.value.checkType, formData.value.projectId, formData.value.assessmentBatchId)
  }
}


const getScoreData = (submitFormData: any, totalScore: any, allAreaScore: any) => {
  formData.value.score = totalScore
  formData.value.totalScore = allAreaScore
  areaRecordList.value = submitFormData

  console.log("submitFormData.value", areaRecordList.value)
}
</script>
